package taskscheduleservicelogic

import (
	"context"
	"github.com/jinzhu/copier"
	"go-zero-admin/application/job/rpc/internal/model"
	"go-zero-admin/application/job/rpc/internal/svc"
	job "go-zero-admin/application/job/rpc/pb"
	"go-zero-admin/pkg/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type ModifyCronLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewModifyCronLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ModifyCronLogic {
	return &ModifyCronLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 任务重新启动和终止
func (l *ModifyCronLogic) ModifyCron(in *job.ModifyScheduleStatusReq) (*job.ModifyScheduleStatusRes, error) {
	var req job.ModifyScheduleStatusReq
	_ = copier.Copy(&req, in)
	var mo model.TaskSchedule
	if err := l.svcCtx.DB.Where("id = ?", req.TaskId).Find(&mo).Error; err != nil {
		return nil, err
	}
	mo.IsOk = !mo.IsOk
	if err := l.svcCtx.DB.Omit("created_at").Save(&mo).Error; err != nil {
		return nil, err
	}
	var res job.ModifyScheduleStatusRes
	res.TaskScheduleInfo = &job.TaskScheduleInfo{}
	_ = copier.Copy(&res.TaskScheduleInfo, &mo)
	res.TaskScheduleInfo.CreatedAt = utils.SafeUnix(&mo.CreatedAt)
	res.TaskScheduleInfo.UpdatedAt = utils.SafeUnix(&mo.UpdatedAt)
	res.TaskScheduleInfo.LastExecuteTime = utils.SafeUnix(mo.LastExecuteTime)
	return &res, nil
}
